<?php
/**
 * Log Task
 * @author	zhangjian<smile_for_life@sina.cn>
 * @date	2014-01-14
 */
 class Task_Log implements ITask
 {
	private $_config = array();
	private $_history = array();
	
	public  $ftp_log_dir = '/www_logs/';// absolute path in ftp server
	public  $local_log_dir = '';// absolute path in local
	
	public function init($config = array())
	{
		$return = false;
		$this->local_log_dir = ROOT_PATH . '/www_logs/';
		
		if($this->_init_config($config)){
			$this->_config = $config;
			$return = true;
		}
		
		return $return;
	}
	
	/**
	 * @param $Re_calc 'on', 'off'
	 */
	public function handle($param = array(), $Re_calc = 'off')
	{
		$return = false;
		
		if($this->_config){
			$Re_calc = strtolower($this->_config['Misc']['Re_calc']);
			if( 'on' == $Re_calc ){
				$gz_file_list = file($this->_config['Ftp'][Ftp::FTP_DOWNLOAD_HISTORY_FILE], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
				$this->history = $gz_file_list;
			}else{
				$ftp = new Ftp($this->_config['Ftp']);
			
				$gz_file_list = $ftp->get_list($this->ftp_log_dir);
				if( is_array($gz_file_list) && $gz_file_list ){

					$this->history = $gz_file_list;
					
					// download log file , .gz format
					foreach($gz_file_list as $gz_file){
						$ftp->get_file($this->ftp_log_dir . $gz_file, $this->local_log_dir . $gz_file);
					}
				}
			}
			
			// call analyse
			$return = $this->_do_sub_task($gz_file_list);

			// Persistence 
			$engine_classname =key($this->_config['Engine']);
			$engine = new $engine_classname;
			$engine->init($this->_config['Engine']);
			$return = $engine->insert($return);
		}
		
		return $return;
	}
	
	/**
	 * clean cache ,history
	 */
	public function clean()
	{
		exit('clean');
	}
	
	private function _init_config(&$config)
	{
		$return = false;
		
		if(is_array($config) && isset($config['Engine'], $config['Ftp'],$config['Task'])){
			$return = true;
		}
		
		return $return;
	}
	
	/**
	 * do sub task
	 * @todo do by thread or process, but php?
	 */
	private function _do_sub_task($log_file_list = array())
	{
		$return = false;
		
		if(is_array($log_file_list) && $log_file_list){
			$gz = new GZ;
			foreach($log_file_list as $log_file){
				$gz->open($this->local_log_dir . '/' . $log_file);
				$data = $gz->read(array('Task_Log_Pv', 'map'), true);

				$sub_task = new Task_Log_Pv;
				$sub_task->reduce($data);
			}
			unset($gz);
			
			$return = $sub_task::$data;
		}
		
		return $return;
	}
	
 }